<template>
  <div>
    <h1 class="page-title">
      <font-awesome-icon icon="brain" />
      用例生成
    </h1>

    <Tabs
      :tabs="tabs"
      default-tab="test-input"
      @tab-change="handleTabChange"
    >
      <template #test-input>
        <div class="content-box">
          <textarea
            v-model="testInput"
            class="input-area"
            placeholder="请输入您的需求文本以生成测试用例..."
          ></textarea>
          <button
            class="btn btn-primary"
            @click="handleGenerate"
            :disabled="loading.testCases"
          >
            <span v-if="loading.testCases" class="loading"></span>
            <font-awesome-icon v-else icon="brain" />
            {{ loading.testCases ? '正在生成...' : '生成测试用例' }}
          </button>
        </div>
      </template>

      <template #test-upload>
        <div class="content-box">
          <FileUploader
            @file-selected="handleFileSelected"
            upload-text="拖拽文件到此处或点击上传"
            upload-subtext="支持Word、PDF和图片文件"
          />
          <button
            class="btn btn-primary"
            @click="handleGenerateFromUpload"
            :disabled="loading.testCases || !uploadedFile"
            style="margin-top: 15px;"
          >
            <span v-if="loading.testCases" class="loading"></span>
            <font-awesome-icon v-else icon="brain" />
            {{ loading.testCases ? '正在解析并生成...' : '解析并生成测试用例' }}
          </button>
        </div>
      </template>
    </Tabs>

    <div class="content-box">
      <h2 class="result-title">解析过程</h2>
      <div class="result-content">
        <div class="analysis-process">
          <div
            v-for="(step, index) in analysisSteps"
            :key="step.id"
            class="analysis-step"
            :class="{ show: step.visible }"
          >
            <div class="analysis-icon">
              <font-awesome-icon :icon="getStepIcon(index)" />
            </div>
            <div class="analysis-text">
              <div class="analysis-title">{{ step.title }}</div>
              <div class="analysis-desc">{{ step.desc }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="content-box">
      <h2 class="result-title">生成的测试用例</h2>
      <div class="result-content">
        <div v-if="loading.testCases" class="result-loading">
          <div v-for="i in 3" :key="i" class="result-loading-table-row"></div>
        </div>
        <div v-else-if="testCases">
          <table class="test-case-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>测试场景</th>
                <th>测试步骤</th>
                <th>预期结果</th>
                <th>优先级</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="(testCase, index) in testCases.test_cases"
                :key="testCase.id"
                :class="{ 'even-row': index % 2 === 1 }"
              >
                <td>{{ testCase.id }}</td>
                <td>{{ testCase.scenario }}</td>
                <td v-html="testCase.steps"></td>
                <td>{{ testCase.expected }}</td>
                <td>{{ testCase.priority }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <p v-else>生成的测试用例将显示在这里...</p>
      </div>
      <button
        class="btn btn-outline"
        @click="handleExport"
        :disabled="!testCases"
      >
        <font-awesome-icon icon="file-excel" />
        导出为Excel
      </button>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import Tabs from '@/components/Tabs.vue';
import FileUploader from '@/components/FileUploader.vue';
import axios from 'axios';

export default {
  name: 'TestCasesPage',
  components: {
    Tabs,
    FileUploader
  },
  data() {
    return {
      tabs: [
        { id: 'test-input', label: '需求输入' },
        { id: 'test-upload', label: '需求上传' }
      ],
      testInput: '请输入您的需求',
      uploadedFile: null,
      activeTab: 'test-input',
      analysisSteps: [
        { id: 'step1', title: '智能解析需求文档', desc: 'AI正在分析需求关键信息...', visible: false },
        { id: 'step2', title: '确定测试场景', desc: '根据需求确定测试场景和测试点...', visible: false },
        { id: 'step3', title: '生成测试用例', desc: '根据测试场景生成详细测试用例...', visible: false }
      ]
    };
  },
  computed: {
    ...mapState(['testCases', 'loading'])
  },
  methods: {
    ...mapActions(['generateTestCases', 'generateTestCasesFromFile', 'showNotification']),

    handleTabChange(tabId) {
      this.activeTab = tabId;
    },

    resetAnalysisSteps() {
      this.analysisSteps.forEach(step => {
        step.visible = false;
      });
    },

    showAnalysisStepsWithDelay() {
      this.analysisSteps.forEach((step, index) => {
        setTimeout(() => {
          step.visible = true;
        }, index * 1000);
      });
    },

    async handleGenerate() {
      if (!this.testInput.trim()) {
        this.showNotification({
          message: '请输入需求内容',
          type: 'error'
        });
        return;
      }

      this.resetAnalysisSteps();
      this.showAnalysisStepsWithDelay();

      try {
        await this.generateTestCases({
          content: this.testInput
        });
      } catch (error) {
        this.handleError(error);
        this.resetAnalysisSteps();
      }
    },

    async handleGenerateFromUpload() {
      if (!this.uploadedFile) {
        this.showNotification({
          message: '请先上传需求文件',
          type: 'error'
        });
        return;
      }

      this.resetAnalysisSteps();
      this.showAnalysisStepsWithDelay();

      try {
        await this.generateTestCasesFromFile({
          file: this.uploadedFile
        });
      } catch (error) {
        this.handleError(error);
        this.resetAnalysisSteps();
      }
    },

    handleFileSelected(file) {
      this.uploadedFile = file;
    },

    async handleExport() {
      if (!this.testCases) {
        this.showNotification({
          message: '没有可导出的内容',
          type: 'error'
        });
        return;
      }

      try {
        const response = await axios.get('/api/test-cases/export', {
          responseType: 'blob',
          params: {
            testCaseId: this.testCases.id
          }
        });

        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `测试用例_${new Date().toISOString().split('T')[0]}.xlsx`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.showNotification({
          message: '测试用例已成功导出为Excel文件',
          type: 'success'
        });
      } catch (error) {
        this.handleError(error);
      }
    },

    getStepIcon(index) {
      const icons = ['brain', 'list-check', 'table'];
      return icons[index] || 'brain';
    },

    handleError(error) {
      let errorMessage = '生成测试用例失败，请重试';
      if (error.response) {
        if (error.response.status === 422) {
          errorMessage = error.response.data.detail?.[0]?.msg || '输入数据格式错误，请检查';
        } else if (error.response.status === 500) {
          errorMessage = '服务器内部错误，请稍后重试';
        }
      }
      this.showNotification({
        message: errorMessage,
        type: 'error'
      });
      console.error(error);
    }
  }
};
</script>

<style scoped>
/* 原有样式保持不变 */
.input-area {
  width: 100%;
  min-height: 200px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  padding: 12px;
  font-size: 14px;
  resize: vertical;
  margin-bottom: 15px;
  font-family: inherit;
}

.result-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #111827;
}

.result-content {
  background-color: #f9fafb;
  border-radius: 6px;
  padding: 15px;
  min-height: 150px;
  margin-bottom: 15px;
  color: #4b5563;
}

/* 分析过程 */
.analysis-process {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.analysis-step {
  display: flex;
  opacity: 0;
  transform: translateY(10px);
  transition: all 0.3s ease;
}

.analysis-step.show {
  opacity: 1;
  transform: translateY(0);
}

.analysis-icon {
  color: #6366f1;
  margin-right: 10px;
  font-size: 18px;
  width: 24px;
  text-align: center;
}

.analysis-text {
  flex: 1;
}

.analysis-title {
  font-weight: 500;
  margin-bottom: 5px;
  color: #111827;
}

.analysis-desc {
  color: #6b7280;
  font-size: 14px;
}

/* 测试用例表格 */
.test-case-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 15px;
}

.test-case-table th,
.test-case-table td {
  border: 1px solid #e5e7eb;
  padding: 10px;
  text-align: left;
}

.test-case-table th {
  background-color: #f3f4f6;
  font-weight: 600;
  color: #374151;
}

.test-case-table .even-row {
  background-color: #f9fafb;
}

/* 加载状态样式 */
.result-loading {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.result-loading-table-row {
  height: 40px;
  background-color: #e5e7eb;
  border-radius: 4px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}
</style>